package com.csun.cmny.provider.controller;

import com.alibaba.fastjson.JSON;
import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.config.RedisInitRunner;
import com.csun.cmny.provider.dao.RoomMapper;
import com.csun.cmny.provider.model.domain.OmcLifeActionOldman;
import com.csun.cmny.provider.model.domain.OmcLifeOldmanRoom;
import com.csun.cmny.provider.model.domain.OmcNursingRoomBind;
import com.csun.cmny.provider.model.dto.BedInfoQueryDto;
import com.csun.cmny.provider.model.dto.life.LifeRoomDto;
import com.csun.cmny.provider.model.dto.life.LifeRoomIndexDto;
import com.csun.cmny.provider.model.dto.life.LifeRoomNotInDto;
import com.csun.cmny.provider.model.dto.life.LifeRoomQueryDto;
import com.csun.cmny.provider.model.vo.*;
import com.csun.cmny.provider.vo.DmcCsunSleepDataVo;
import com.csun.cmny.provider.model.vo.csunsleep.DmcCsunSleepVo;
import com.csun.cmny.provider.model.vo.csunsleep.SleepAndAlert;
import com.csun.cmny.provider.model.vo.life.LifeIndexRoomVO;
import com.csun.cmny.provider.model.vo.life.LifeRoomVO;
import com.csun.cmny.provider.pojo.Bed;
import com.csun.cmny.provider.pojo.Building;
import com.csun.cmny.provider.pojo.Room;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.validator.OmcLifeRoomAddValidator;
import com.csun.cmny.provider.vo.*;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.*;

/*
 * 房间管理
 * */
@Slf4j
@RestController
@RequestMapping("/Room")
public class RoomController extends BaseController {

    @Resource
    private RedisInitRunner redisInitRunner;
    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Autowired
    private RoomService roomService;
    @Resource
    private RoomMapper roomMapper;
    @Autowired
    private BedService bedService;
    @Autowired
    private BuildingService buildingService;
    @Resource
    private OmcNursingRoomBindService omcNursingRoomBindService;
    @Resource
    private DmcRpcService dmcRpcService;
    @Resource
    private OmcLifeActionOldmanService omcLifeActionOldmanService;
    @Resource
    private OmcLifeOldmanRoomService omcLifeOldmanRoomService;
    @Resource
    private OmcLevelCareService levelCareService;

    /*
     * 这里的认证和当前登录的用户注解先预留，等完善了再进行修改
     * 1.判断该用户是否属于该机构人员
     * */
    //添加房间
    @RequestMapping(value = "/addRoom", method = RequestMethod.POST)
    public Wrapper addRoom(Room room) {
        //校验
        if (StringUtils.isEmpty(room.getRoomNo())) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.no.null", null));
        }
        if (room.getBedNum() == null) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "床位数量不能为空", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("bed.num.null", null));
        }
        if (room.getHasToilet() == null) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "是否有厕所不能为空", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("bed.wc.null", null));
        }
        if (room.getBuildingId() == null) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "楼栋id不能为空", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("building.id.null", null));
        }
        if (StringUtils.isEmpty(room.getFloorNo())) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "楼层号不能为空", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("floor.no.null", null));
        }
        if (room.getRoomType() == null) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "房间类型不能为空", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.type.null", null));
        }
        if (room.getRoomDirection() == null) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "房间朝向不能为空", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.direction.null", null));
        }
        if (room.getRoomNo().length() > 12) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "房间编号不能大于12位", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.no.size.12", null));
        }
        if (room.getFloorNo() > 999) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "楼层号不能大于3位", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("floor.no.size.3", null));
        }

        //判断该楼层号是否超出了该楼栋的最大楼层值
        Building building = buildingService.selectById(room.getBuildingId());
        if (building == null) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "要添加的房间所在的楼栋不存在", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("building.name.null", null));
        } else if (building.getFloorNum() < room.getFloorNo()) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "要添加的房间的楼层号超过了该楼栋楼层的最大层值", building.getFloorNum());
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.floor.size", null));
        }
        //判断该房间名称是否已经在该社区中存在
        Room room1 = new Room();
        room1.setRoomNo(room.getRoomNo());
        room1.setBuildingId(room.getBuildingId());
        Room room2 = roomService.selectByRoom(room1);
        if (room2 != null) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "该编号的房间已经在该社区中存在", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("no.exist.error", null));
        }
        /**
         * @date 2019-05-06
         * @author chisj
         * @desc 校验房间别名
         */
        // 校验房间别名是否在楼栋中已经存在
//        Room roomCheck = new Room();
//        roomCheck.setRoomAlias(room.getRoomAlias());
//        roomCheck.setBuildingId(room.getBuildingId());
//        if (!roomService.checkRoomAlias(roomCheck)) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, "房间别名已经存在.", null);
//        }

        //插入房间
        /*if (PublicUtil.isNotEmpty(room.getLevelCareId())){
            OmcLevelCare omcLevelCare = levelCareService.selectByKey(room.getLevelCareId());
            if (PublicUtil.isEmpty(omcLevelCare)){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                        .getMessage("levelCare.the.null", null));
            }
            room.setLevelCareName(omcLevelCare.getNursingCare());
        }*/
        int n = roomService.insert(room);
        if (n <= 0) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //添加床位
        if (room.getBedNum() > 0) {
            //查询该楼栋的床位编号方式(1 按房间计数 2 按楼层计数)及房间信息
            Map<String, Object> buildingAndRoom = roomService.selectBuildingAndRoom(room.getRoomId());
            //获取编号方式
            Integer bedNoType = (Integer) buildingAndRoom.get("bedNoType");
            //床位集合
            List<Bed> bedList = new ArrayList<>();
            for (int i = 1; i <= room.getBedNum(); i++) {
                Bed bed = new Bed();
                bed.setRoomId(room.getRoomId());
                if(room.getLevelCareId() != null){
                    bed.setLevelCareId(room.getLevelCareId());
                }
                bed.setModifier(1L);
                if (bedNoType != null && bedNoType == 1) {
                    bed.setBedNo(i);
                    bedList.add(bed);
                } else if (bedNoType != null && bedNoType == 2) {
                    //根据楼栋id和楼层号查询出该层床位号最大的床位号
                    List<Map<String, Object>> mapList = roomService.selectByBidAndFno(room.getBuildingId(), room.getFloorNo());
                    bed.setBedNo(i);
                    if (CollectionUtils.isEmpty(mapList)) {
//                       bed.setBedNo(i);
                        bedList.add(bed);
                    } else {
                        //取得当前层的最大床位编号
                        Integer bedNo = (Integer) mapList.get(0).get("bedNo");
                        if (PublicUtil.isNotEmpty(bedNo)) {
                            bed.setBedNo(bedNo + i);
                        }
                        bedList.add(bed);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(bedList)) {

                //批量插入床位
                int m = bedService.insertBatch(bedList);
                if (m <= 0) {
                    System.out.println("********************添加房间时批量插入床位失败********************");
                }
            }
        }

        //return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "添加成功", n);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),n);
    }

    //根据id删除房间
    @RequestMapping(value = "/delRoomById", method = RequestMethod.POST)
    public Wrapper delRoomById(Integer roomId) {
        if (roomId == null) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.id.null", null));
        }
        Room roomQuery = roomService.selects(roomId);
//        if (room.getBedNum() > 0) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, "该房间有床位,不能删除", roomId);
//        }
        List<Bed> bedList = roomQuery.getBedList();
        for(Bed bed : bedList){
            if(bed.getOldmanId() != null){
                //return WrapMapper.wrap(Wrapper.ERROR_CODE, "该房间有老人入住,不能删除", roomId);
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                        .getMessage("room.man.del", null));
            }
        }
        for(Bed bed : bedList){
            int bedDel = bedService.deleteById(bed.getBedId());
        }
        //删除房间
        int m = roomService.deleteById(roomId);

        //删除与护工组的绑定
        OmcNursingRoomBind omcNursingRoomBind = new OmcNursingRoomBind();
        omcNursingRoomBind.setRoomId(roomId.longValue());
        int n = omcNursingRoomBindService.delete(omcNursingRoomBind);

        if (m <= 0) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "没有此id", roomId);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("Examine.not.id", null));
        }
        //return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "删除成功", m);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),m);
    }

    //修改房间——不能修改房间的床位数量，如果要加床或者减床去床位管理模块进行逐一操作
    //原因：1.涉及到床位编号的方式 2.当床位数量减少时，不知道具体删除哪个床位且万一要删除的床位有老人入住了。
    //太多不确定因素
    @RequestMapping(value = "/updateRoom", method = RequestMethod.POST)
    public Wrapper updateRoom(Room room) {
        //校验
        if (room.getRoomId() == null) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "房间id不能为空", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.id.null", null));
        }

        if (room.getBedNum() != null) {
            Room room1 = roomService.selectById(room.getRoomId());
            if (room1 != null) {
                if (room1.getBedNum().intValue() != room.getBedNum().intValue()) {
                    //return WrapMapper.wrap(Wrapper.ERROR_CODE, "不能修改房间的床位数量", null);
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                            .getMessage("bed.no.update", null));
                }
            }
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "根据房间id未查询到房间", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.id.query.null", null));
        }
        //判断该楼层号是否超出了该楼栋的最大楼层值
        Building building = buildingService.selectById(room.getBuildingId());
        if (building == null) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "要修改的房间所在的楼栋不存在", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("building.room.null", null));
        }
        if (room.getFloorNo() != null && building.getFloorNum() < room.getFloorNo()) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "要修改的房间的楼层号超过了该楼栋楼层的最大层值", building.getFloorNum());
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.floor.size", null));
        }
        if (room.getFloorNo() > 999) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "楼层号不能大于3位", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("floor.no.size.3", null));
        }
        //判断该房间编号是否已经在该社区中存在
        Room room1 = new Room();
        if (StringUtils.isEmpty(room.getRoomNo())) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "房间编号不能为空", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.no.null", null));
        }

        /**
         * @date 2019-05-06
         * @author chisj
         * @desc 校验房间别名
         */
        // 校验房间别名是否存在
        Room roomCheck = new Room();
        roomCheck.setRoomId(room.getRoomId());
        roomCheck.setBuildingId(room.getBuildingId());
        if(room.getRoomAlias() != null && !room.getRoomAlias().equals("")){
            roomCheck.setRoomAlias(room.getRoomAlias());
           //房间别名可重复
//            if (!roomService.checkRoomAlias(roomCheck)) {
//                return WrapMapper.wrap(Wrapper.ERROR_CODE, "房间别名已经存在", null);
//            }
        }

        if (room.getRoomNo().length() > 12) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "房间号不能大于12位", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.no.size.12", null));
        }
        room1.setRoomNo(room.getRoomNo());
        room1.setBuildingId(room.getBuildingId());
        Room room2 = roomService.selectByRoom(room1);
        if (room2 != null && room2.getRoomId().intValue() != room.getRoomId().intValue()) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "该编号的房间已经在该社区中存在", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("no.exist.error", null));
        }
        //修改
       /* if (PublicUtil.isNotEmpty(room.getLevelCareId())){
            OmcLevelCare omcLevelCare = levelCareService.selectByKey(room.getLevelCareId());
            if (PublicUtil.isEmpty(omcLevelCare)){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                        .getMessage("levelCare.the.null", null));
            }
            room.setLevelCareName(omcLevelCare.getNursingCare());
        }*/
        int n = roomService.updateById(room);
        if (n <= 0) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "修改失败", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("comment.update.fail", null));
        }

        // redis更新房间
        redisInitRunner.refreshRoom(room.getRoomId());
        // redis更新床位
        redisInitRunner.refreshRoomBed(room.getRoomId());

        //return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "修改成功", n);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),n);
    }

    //根据房间id查询房间信息——只有房间信息
    @RequestMapping(value = "/selectById", method = RequestMethod.POST)
    public Wrapper selectById(Integer roomId) {
        //校验
        if (roomId == null) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "房间id不能为空", roomId);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.id.null", null));
        }
        Room room = roomService.selectById(roomId);
        if (room == null) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "没有此id", roomId);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("Examine.not.id", null));
        }
        //return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "查询成功", room);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),room);
    }

    //根据房间id查询房间信息——只有房间信息
    @RequestMapping(value = "/selects", method = RequestMethod.POST)
    public Wrapper selects(Integer roomId) {
        //校验
        if (roomId == null) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "房间id不能为空", roomId);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.id.null", null));
        }
        Room room = roomService.selects(roomId);
        if (room == null) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "没有此id", roomId);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("Examine.not.id", null));
        }
        //return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "查询成功", room);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),room);
    }

    //buildingId和楼层号查询某层房间及床位信息
    @RequestMapping(value = "/showAll", method = RequestMethod.POST)
    public Wrapper showAll(Room room) {
        if (room.getBuildingId() == null) {
            //return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, "楼栋id不能为空", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("building.id.null", null));
        }
        //查询该楼栋的基本信息
        Building building = buildingService.selectById(room.getBuildingId());
        if (building == null) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "楼栋id不存在", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("building.id.null", null));
        }
        //查询到的房间集合
        List<RoomWithOtherVo> roomList = roomService.selectRoomsWithOther(room);
        if (CollectionUtils.isEmpty(roomList)) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "该楼层未添加房间", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("floor.room.null", null));
        }
        //楼层集合
        List<FloorWithOtherVo> floorList = new ArrayList<>();
        //当room没有给floorNo值时表示查询的是整栋楼的信息
        if (room.getFloorNo() == null) {
            //按照层进行循环，获取每层对应的房间
            for (int i = 0; i < building.getFloorNum(); i++) {
                FloorWithOtherVo floor = new FloorWithOtherVo();
                List<RoomWithOtherVo> roomList1 = new ArrayList<>();
                floor.setFloorNo(i + 1);
                for (int j = 0; j < roomList.size(); j++) {
                    if (roomList.get(j).getFloorNo() == (i + 1)) {
                        roomList1.add(roomList.get(j));
                    }
                }
                floor.setRoomList(roomList1);
                floorList.add(floor);
            }
        } else {
            FloorWithOtherVo floor = new FloorWithOtherVo();
            floor.setFloorNo(room.getFloorNo());
            floor.setRoomList(roomList);
            floorList.add(floor);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("building", building);
        map.put("floorList", floorList);
       // return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "查询成功", map);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),map);
    }

    /**
     * 房间房间别名是否重复
     *
     * @param room
     * @return
     */
    @PostMapping(value = "/checkRoomAlias")
    public Wrapper checkRoomAlias(Room room) {

        if (!roomService.checkRoomAlias(room)) {
            //return WrapMapper.wrap(Wrapper.ERROR_CODE, "房间别名已经存在", null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("name.exist.error", null));
        }

        //return WrapMapper.ok();
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null));
    }

    /**
     * 根据楼栋、楼层查询房间信息
     *
     * @param: [buildingId, floorNo]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @ValidateAnnotation
    @RequestMapping(value = "/queryRoomInfo", method = RequestMethod.POST)
    public Wrapper queryRoomInfo(@RequestBody BedInfoQueryDto bedInfoQueryDto) {
        List<RoomInfoVo> voList = roomService.queryRoomInfo(bedInfoQueryDto.getBuildingId(),bedInfoQueryDto.getFloorNo(),bedInfoQueryDto.getRoomId(),getLoginAuthDto());
        //return WrapMapper.ok(voList);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),voList);
    }

    /*life项目居室一览*/
    @ValidateAnnotation
    @RequestMapping(value = "/queryRoomInfoLife", method = RequestMethod.POST)
    public Wrapper queryRoomInfolife() {
        List<RoomInfoLifeVo> voList = roomService.queryRoomInfoLife();
        //return WrapMapper.ok(voList);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),voList);
    }

    /**
     * life房间-添加
     * @date 2019/12/31 11:01
     * @param dto
     * @return com.csun.cmny.provider.controller.RoomController
     */
    @PostMapping(value = "/lifeRoom")
    public Wrapper addLifeRoom(@Validated(OmcLifeRoomAddValidator.class) @RequestBody LifeRoomDto dto){
        Integer result = saveLifeRoom(dto,getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    /**
     * life房间-修改
     * @date 2019/12/31 13:23
     * @param lifeRoomDto, br
     * @return com.csun.cmny.provider.controller.RoomController
     */
    @PutMapping(value = "/lifeRoom")
    public Wrapper edit(LifeRoomDto lifeRoomDto) {
        if(lifeRoomDto.getId() == null || lifeRoomDto.getId().equals(0L)){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("config.id.null", null));
        }
        /**
         * @Auther: ZNR
         * @Date: 2021-01-13
         * 房间类型中有厕所修改为无厕所时，若已绑定人感，则提示先解绑
         */
        LifeRoomVO lifeRoom = roomMapper.getLifeRoomById(lifeRoomDto.getId().intValue());
        Long isBind = roomMapper.isBindBodySensorByRoomId(lifeRoomDto.getId().intValue());
        if (lifeRoom.getHasToilet()==1 && lifeRoomDto.getHasToilet()==0 && isBind != null){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("config.hastoilet.bodysensor", null));
        }

        Integer result = saveLifeRoom(lifeRoomDto,getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        OmcLifeOldmanRoom omcLifeOldmanRoom = new OmcLifeOldmanRoom();
        omcLifeOldmanRoom.setRoomId(lifeRoomDto.getId());
        OmcLifeOldmanRoom omcLifeOldmanRoom1 = omcLifeOldmanRoomService.selectOne(omcLifeOldmanRoom);
        if (!PublicUtil.isEmpty(omcLifeOldmanRoom1)){
            Building b  =buildingService.selectById(lifeRoomDto.getBuildingId().intValue());
            OmcLifeActionOldman omcLifeActionOldman = new OmcLifeActionOldman();
            omcLifeActionOldman.setOldmanId(omcLifeOldmanRoom1.getOldmanId());
            omcLifeActionOldman.setBuildingName(b.getBuildingName());
            omcLifeActionOldman.setFloor(lifeRoomDto.getFloorNo().toString());
            omcLifeActionOldman.setRoomNo(lifeRoomDto.getRoomNo());
            int ret = omcLifeActionOldmanService.update(omcLifeActionOldman);
            if(ret<1){
                return WrapMapper.wrap(Wrapper.ERROR_CODE,(null));
            }
        }
        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    /**
     * 分页查询
     *
     * @date 2019/12/24 16:25
     *
     * @param lifeRoomQuertDto
     *
     * @return com.csun.cmny.provider.controller.life.OmcLifeRoomController
     */
    @GetMapping(value = "/listLifeRooms")
    public Wrapper listLifeRooms(LifeRoomQueryDto lifeRoomQuertDto,
                                 BindingResult br) {
        if(lifeRoomQuertDto.getGroupId() == null || lifeRoomQuertDto.getGroupId().equals(0)){
            lifeRoomQuertDto.setGroupId(getLoginAuthDto().getGroupId());
        }
        PageHelper.startPage(lifeRoomQuertDto.getPageNum(), lifeRoomQuertDto.getPageSize());
        List<LifeRoomVO> roomList = roomService.queryListWithPage(lifeRoomQuertDto);
        //return WrapMapper.ok();
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), new PageInfo<>(roomList));
    }

    /**
     * life-房间详情
     * @date 2019/12/31 13:19
     * @param roomId
     * @return com.csun.cmny.provider.controller.RoomController
     */
    @GetMapping(value = "/lifeRoom")
    public Wrapper listLifeRoom(@RequestParam Long roomId) {
        if(roomId == null || roomId.equals(0L)){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("room.id.null", null));
        }
        LifeRoomVO vo = roomService.getById(roomId);
        //return WrapMapper.ok(vo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), vo);
    }

    /**
     * 删除
     *
     * @date 2019/12/24 16:26
     *
     * @param lifeRoomId, br
     *
     * @return com.csun.cmny.provider.controller.life.OmcLifeRoomController
     */
    @DeleteMapping(value = "/lifeRoom/{lifeRoomId}")
    public Wrapper deleteById(@PathVariable Long lifeRoomId) {
        Integer result = roomService.deleteLifeRoomById(lifeRoomId);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), result);
    }

    /*life首页房间信息*/
    @RequestMapping(value = "/listLifeIndexRooms", method = RequestMethod.POST)
    public Wrapper listLifeIndexRooms(@RequestBody LifeRoomIndexDto lifeRoomIndexDto) {
        if(lifeRoomIndexDto.getGroupId() == null || lifeRoomIndexDto.getGroupId().equals(0)){
            lifeRoomIndexDto.setGroupId(getLoginAuthDto().getGroupId());
        }
        List<LifeIndexRoomVO> roomList = roomService.queryIndexRooms(lifeRoomIndexDto);


        for (LifeIndexRoomVO lifeIndexRoomVO : roomList) {
          //  Map deviceData=dmcRpcService.selectDeviceDataByRoomId(lifeIndexRoomVO.getId());
            Map alertData=dmcRpcService.selectAlertDataByRoomId(lifeIndexRoomVO.getId(),getLoginAuthDto().getGroupId());
          /*  if(PublicUtil.isNotEmpty(deviceData)){
                lifeIndexRoomVO.setTemperature((String) deviceData.get("temperature"));
                lifeIndexRoomVO.setHeartbeat((String) deviceData.get("heartbeat"));
                lifeIndexRoomVO.setBreath((String) deviceData.get("breath"));
            }*/
            if(PublicUtil.isNotEmpty(alertData)){
                lifeIndexRoomVO.setDeviceAlert((List<DmcDeviceAlert>) alertData.get("deviceAlert"));
            }
            IsInRoomVO isInRoomVO = dmcRpcService.getIsInRoomStatus(lifeIndexRoomVO.getId());
            if(PublicUtil.isNotEmpty(isInRoomVO)){
                lifeIndexRoomVO.setIsInRoom(isInRoomVO.getIsInRoom());
                lifeIndexRoomVO.setIsDeviceEnough(isInRoomVO.getIsDeviceEnough());
            }

        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), roomList);
    }

    /*life房间具体信息*/
    @RequestMapping(value = "/theLifeRoom/{roomId}", method = RequestMethod.POST)
    public Wrapper theLifeRoom(@PathVariable Long roomId) {

        List<LifeIndexRoomVO> roomList = roomService.lifeRoom(roomId,getLoginAuthDto().getGroupId());

        for (LifeIndexRoomVO lifeIndexRoomVO : roomList) {
            Map deviceData=dmcRpcService.selectDeviceDataByRoomId(lifeIndexRoomVO.getId());


            if(PublicUtil.isNotEmpty(deviceData)){
                lifeIndexRoomVO.setTemperature((String) deviceData.get("temperature"));
                lifeIndexRoomVO.setHeartbeat((String) deviceData.get("heartbeat"));
                lifeIndexRoomVO.setBreath((String) deviceData.get("breath"));
                lifeIndexRoomVO.setInBed((String) deviceData.get("in_bed"));
            }

        }

        //return WrapMapper.ok(roomList);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), roomList);
    }

    /**
     * 查询为未住的房间
     * @date 2020/01/06 16:25
     * @param lifeRoomNotInDto
     * @return com.csun.cmny.provider.controller.life.OmcLifeRoomController
     */
    @GetMapping(value = "/notLifeRooms")
    public Wrapper notLifeRooms(LifeRoomNotInDto lifeRoomNotInDto,
                                 BindingResult br) {
        if(lifeRoomNotInDto.getGroupId() == null || lifeRoomNotInDto.getGroupId().equals(0)){
            lifeRoomNotInDto.setGroupId(getLoginAuthDto().getGroupId());
        }
        LifeRoomQueryDto lifeRoomQuertDto = new LifeRoomQueryDto();
        BeanUtils.copyProperties(lifeRoomNotInDto,lifeRoomQuertDto);
        List<LifeRoomVO> roomList = roomService.notLifeRooms(lifeRoomQuertDto);
        if(lifeRoomNotInDto.getRoomId() != null && lifeRoomNotInDto.getRoomId()>0) {
            LifeRoomVO vo = roomService.getById(lifeRoomNotInDto.getRoomId());
            if (!PublicUtil.isEmpty(vo) && lifeRoomNotInDto.getBuildingId().equals(vo.getBuildingId()) &&
                    lifeRoomNotInDto.getFloorNo().equals(vo.getFloorNo())) {
                roomList.add(vo);
            }
        }
        //return WrapMapper.ok(roomList);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), roomList);
    }

    /**
     * life房间-保存
     * @date 2019/12/31 11:02
     * @param lifeRoomDto, loginAuthDto
     * @return com.csun.cmny.provider.controller.RoomController
     */
    private Integer saveLifeRoom(LifeRoomDto lifeRoomDto, LoginAuthDto loginAuthDto) {
        Room room = new Room();
        room.setRoomNo(lifeRoomDto.getRoomNo());
        room.setBuildingId(lifeRoomDto.getBuildingId().intValue());
        room.setFloorNo(lifeRoomDto.getFloorNo());
        room.setHasToilet(lifeRoomDto.getHasToilet());
        if(lifeRoomDto.getId() != null){
            room.setRoomId(lifeRoomDto.getId().intValue());
        }
        if(lifeRoomDto.getGroupId() != null && !lifeRoomDto.getGroupId().equals(0)){
            loginAuthDto.setGroupId(lifeRoomDto.getGroupId());
        }
        return roomService.saveLifeRoom(room, loginAuthDto);
    }
    /**
      * 守护佳个人床垫数据
     * @return Wrapper
     * @author HD
     * @date 2021/12/16 10:08
     */
    @PostMapping("/roomSleepInfo")
    public Wrapper roomSleepInfo(){
        Long groupId = getLoginAuthDto().getGroupId();
        //查询床垫信息
        SleepAndAlert sleepAndAlert = dmcRpcService.queryGroupCsunSleepListByGroupId(groupId);
        List<DmcCsunSleepVo> csunSleepVos = sleepAndAlert.getCsunSleepVos();
        List<DmcDeviceAlert> deviceAlerts = sleepAndAlert.getDeviceAlerts();
        List<DmcCsunSleepDataVo> csunSleepDatas = sleepAndAlert.getCsunSleepDatas();
        ArrayList<Long> ids = new ArrayList<>();
        for (DmcCsunSleepVo d:csunSleepVos) {
            ids.add(d.getOldmanId().longValue());
        }
        //查询老人楼栋信息
        List<RoomSleepInfo> roomSleepInfolist = roomService.queryRoomSleepInfo(ids);
        for (RoomSleepInfo r:roomSleepInfolist) {
            for (DmcCsunSleepVo ds:csunSleepVos) {
                if(r.getOldmanId().equals(ds.getOldmanId().longValue())){
                    r.setDeviceId(ds.getId());
                }
            }
        }
        for (RoomSleepInfo r:roomSleepInfolist) {
            for (DmcCsunSleepDataVo ds:csunSleepDatas) {
                if(r.getDeviceId().equals(ds.getDeviceId())){
                    r.setHeartbeat(ds.getHeartbeat());
                    r.setBreath(ds.getBreath());
                    r.setInBed(ds.getInBed());
                    r.setStatus(ds.getStatus());
                }
            }
        }
        for (RoomSleepInfo r:roomSleepInfolist) {
            List<DmcDeviceAlert> dmcDeviceAlerts = new ArrayList<>();
            for (DmcDeviceAlert ds:deviceAlerts) {
                if(r.getDeviceId().equals(ds.getDeviceId())){
                    dmcDeviceAlerts.add(ds);
                    r.setDeviceAlert(dmcDeviceAlerts);
                    break;
                }
            }
        }
        /*ArrayList<Long> ids = new ArrayList<>();
        for (DmcCsunSleepVo dmcCsunSleepVo:dmcCsunSleepVos) {
            RoomSleepInfo roomSleepInfo = new RoomSleepInfo();
            if(dmcCsunSleepVo.getOldmanId() != null){
                ids.add(dmcCsunSleepVo.getOldmanId().longValue());
                BeanUtils.copyProperties(dmcCsunSleepVo,roomSleepInfo);
                roomSleepInfo.setOldmanId(dmcCsunSleepVo.getOldmanId().longValue());
                roomSleepInfo.setOldName(dmcCsunSleepVo.getOldmanName());
                roomSleepInfo.setDeviceId(dmcCsunSleepVo.getId());
                roomSleepInfos.add(roomSleepInfo);
            }
        }

        List<RoomSleepInfo> roomSleepInfolist = roomService.queryRoomSleepInfo(ids);
        for (RoomSleepInfo d :roomSleepInfos) {
            for (RoomSleepInfo r:roomSleepInfolist) {
                if(d.getOldmanId().equals(r.getOldmanId())){
                    r.setDeviceId(d.getDeviceId());
                    BeanUtils.copyProperties(r,d);

                }
            }
        }
        ids= new ArrayList<>();
        for (RoomSleepInfo s:roomSleepInfolist) {
            ids.add(s.getDeviceId());
        }
        //查询床垫数据
        List<Map> deviceData=dmcRpcService.querySleepInfoByRoomId(ids);
        if(deviceData.size() > 0){
            List<LifeSleepDataIndex>  lifeSleepDataIndex = (List<LifeSleepDataIndex>) deviceData.get(0).get("lifeSleepDataIndex");
            for (Map map:deviceData) {
                for (RoomSleepInfo rs:roomSleepInfolist) {
                    if(rs.getOldmanId() !=null && rs.getOldmanId().equals(Long.valueOf(map.get("oldmanId").toString()))){
                        rs.setOldmanId(Long.valueOf(map.get("oldmanId").toString()));
                        rs.setInBed(Integer.valueOf(map.get("in_bed").toString()) );
                        rs.setBreath(Integer.valueOf(map.get("breath").toString()));
                        rs.setHeartbeat(Integer.valueOf(map.get("heartbeat").toString()));
                        //判断报警
                        List<DmcDeviceAlert> deviceAlerts = new ArrayList<>();
                        //放入报警信息
                        if(lifeSleepDataIndex.size() > 0){
                            for (Object o:lifeSleepDataIndex) {
                                String s = JSON.toJSONString(o);
                                LifeSleepDataIndex r = JSON.parseObject(s, LifeSleepDataIndex.class);
                                if(r.getOldmanId().equals(rs.getOldmanId()) && r.getIsHandle()!= null && r.getIsHandle() ==0){
                                    DmcDeviceAlert deviceAlert = new DmcDeviceAlert();
                                    deviceAlert.setOldmanId(r.getOldmanId().intValue());
                                    deviceAlert.setDeviceId(Long.valueOf(r.getDeviceID()));
                                    if(r.getAlertType() != null){
                                        deviceAlert.setAlertType(Integer.valueOf(r.getAlertType()));
                                    }
                                    deviceAlert.setAlertInfo(r.getAlertInfo());
                                    deviceAlert.setId(r.getId());
                                    deviceAlerts.add(deviceAlert);
                                }
                                rs.setDeviceAlert(deviceAlerts);
                                break;
                            }
                        }
                    }
                }
            }
        }
        //查询床垫状态
        List<SleepDataVo> sleepDataIndexList = dmcRpcService.queryInBed(ids);
        if(sleepDataIndexList != null){
            for(RoomSleepInfo s:roomSleepInfolist){
                for (SleepDataVo l:sleepDataIndexList) {
                    if(s.getDeviceId() != null && s.getDeviceId().equals(l.getDeviceId())){
                        s.setStatus(l.getStatus());
                        s.setInBed(l.getInBed());
                    }
                }
            }
        }*/
        /*排序*/
        List<RoomSleepInfo> roomSleepInfoList = new ArrayList<>();
        for (RoomSleepInfo rs:roomSleepInfolist) {
            if(rs.getDeviceAlert().size() > 0) {
                roomSleepInfoList.add(rs);
            }
        }
        for (RoomSleepInfo rs:roomSleepInfolist) {
            if(rs.getDeviceAlert().size() != 1 && rs.getStatus().equals("online")){
                roomSleepInfoList.add(rs);
            }
        }
        for (RoomSleepInfo rs:roomSleepInfolist) {
            if(rs.getDeviceAlert().size() != 1 && rs.getStatus().equals("offline")){
                roomSleepInfoList.add(rs);
            }
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), roomSleepInfoList);
    }

    /**
     * 查询床垫报警
      * @param isHandle
     * @return null
     * @author HD
     * @date 2021/12/16 19:51
     */
    @PostMapping("/querySleepAlertInfo")
    public Wrapper querySleepAlertInfo(Integer isHandle,Integer pageNum,Integer pageSize){
        Long groupId = getLoginAuthDto().getGroupId();
        List<RoomSleepInfo> roomSleepInfos = roomService.roomSleepInfo(groupId);
        ArrayList<Long> ids = new ArrayList<>();
        if(roomSleepInfos.size()>0){
            for (RoomSleepInfo r:roomSleepInfos){
                ids.add(r.getOldmanId());
            }
        }
        //查询报警信息
        PageInfo deviceAlert = dmcRpcService.querySleepAlertInfo(ids,isHandle,pageNum,pageSize);
        List devices = deviceAlert.getList();
        List<SleepAlertInfo> list = new ArrayList<>();
        for (Object o :devices) {
            String s = JSON.toJSONString(o);
            DmcDeviceAlert alert = JSON.parseObject(s, DmcDeviceAlert.class);
            SleepAlertInfo sleepAlertInfo = new SleepAlertInfo();
            BeanUtils.copyProperties(alert,sleepAlertInfo);
            sleepAlertInfo.setOldName(alert.getOldmanName());
            sleepAlertInfo.setOldmanId(alert.getOldmanId().longValue());
            for (RoomSleepInfo sleep:roomSleepInfos) {
                if(sleepAlertInfo.getOldmanId().equals(sleep.getOldmanId())){
                    sleepAlertInfo.setOldName(sleep.getOldName());
                    sleepAlertInfo.setSex(sleep.getSex());
                    list.add(sleepAlertInfo);
                }
            }
        }
        deviceAlert.setList(list);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), deviceAlert);
    }

    /**
     * 守护家床垫首页
     * @return
     */
    @PostMapping("/sleepAlertIndex")
    public Wrapper sleepAlertIndex(){
//        Long groupId = getLoginAuthDto().getGroupId();
//        //查询床垫绑定
//        List<DmcCsunSleepVo> dmcCsunSleepVos = dmcRpcService.queryGroupCsunSleepList(groupId);
//        List<RoomSleepInfo> roomSleepInfos = new ArrayList<>();
//        ArrayList<Long> ids = new ArrayList<>();
//        for (DmcCsunSleepVo dmcCsunSleepVo:dmcCsunSleepVos) {
//            RoomSleepInfo roomSleepInfo = new RoomSleepInfo();
//            if(dmcCsunSleepVo.getOldmanId() != null){
//                ids.add(dmcCsunSleepVo.getOldmanId().longValue());
//                BeanUtils.copyProperties(dmcCsunSleepVo,roomSleepInfo);
//                roomSleepInfo.setOldmanId(dmcCsunSleepVo.getOldmanId().longValue());
//                roomSleepInfo.setOldName(dmcCsunSleepVo.getOldmanName());
//                roomSleepInfo.setDeviceId(dmcCsunSleepVo.getId());
//                roomSleepInfos.add(roomSleepInfo);
//            }
//        }
//        if(ids.size() == 0){
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
//                    .getMessage("operation.failed", null));
//        }
//        //查询报警信息
//        List<DmcDeviceAlert> deviceAlerts = dmcRpcService.queryAllSleepAlert(ids);
//        List<RoomSleepInfo> oldmanList = roomMapper.selectOldmanSex(ids);
//        for (RoomSleepInfo r:roomSleepInfos) {
//            for (RoomSleepInfo rs:oldmanList) {
//                if(r.getOldmanId().equals(rs.getOldmanId())){
//                    r.setSex(rs.getSex());
//                }
//            }
//        }
//        List<SleepAlertInfo> list = new ArrayList<>();
//        for (DmcDeviceAlert alert:deviceAlerts) {
//            SleepAlertInfo sleepAlertInfo = new SleepAlertInfo();
//            BeanUtils.copyProperties(alert,sleepAlertInfo);
//            sleepAlertInfo.setOldName(alert.getOldmanName());
//            sleepAlertInfo.setOldmanId(alert.getOldmanId().longValue());
//            list.add(sleepAlertInfo);
//        }
//        //查询绑定了床垫的老人
//        List<RoomSleepInfo> sleepInfos = dmcRpcService.querySleepBind(ids);
//        for (RoomSleepInfo r:sleepInfos) {
//            for (RoomSleepInfo s :roomSleepInfos ) {
//                if(r.getOldmanId().equals(s.getOldmanId())){
//                    r.setSex(s.getSex());
//                    break;
//                }
//            }
//        }
//
//        //查询床垫状态
//        List<Long> deviceIds = new ArrayList<>();
//        for (RoomSleepInfo s:sleepInfos) {
//            deviceIds.add(s.getDeviceId());
//        }
//        List<SleepDataVo> sleepDataIndexList = dmcRpcService.queryInBed(deviceIds);
//        if(sleepDataIndexList != null){
//            for(RoomSleepInfo s:sleepInfos){
//                for (SleepDataVo l:sleepDataIndexList) {
//                    if(s.getDeviceId().equals(l.getDeviceId())){
//                        s.setInBed(Integer.valueOf(l.getInBed()));
//                        s.setStatus(l.getStatus());
//                    }
//                }
//            }
//        }
//
//        Set<Long> set = new HashSet<>();
//        for (SleepAlertInfo s:list) {
//            set.add(s.getOldmanId());
//        }
        Long groupId = getLoginAuthDto().getGroupId();
        //查询床垫信息
        SleepAndAlert sleepAndAlert = dmcRpcService.queryGroupCsunSleepListByGroupId(groupId);
        List<DmcCsunSleepVo> csunSleepVos = sleepAndAlert.getCsunSleepVos();
        List<DmcDeviceAlert> deviceAlerts = sleepAndAlert.getDeviceAlerts();
        List<DmcCsunSleepDataVo> csunSleepDatas = sleepAndAlert.getCsunSleepDatas();
        ArrayList<Long> ids = new ArrayList<>();
        for (DmcCsunSleepVo d:csunSleepVos) {
            ids.add(d.getOldmanId().longValue());
        }
        //查询老人楼栋信息
        List<RoomSleepInfo> roomSleepInfolist = roomService.queryRoomSleepInfo(ids);
        for (RoomSleepInfo r:roomSleepInfolist) {
            for (DmcCsunSleepVo ds:csunSleepVos) {
                if(r.getOldmanId().equals(ds.getOldmanId().longValue())){
                    r.setDeviceId(ds.getId());
                }
            }
        }
        for (RoomSleepInfo r:roomSleepInfolist) {
            for (DmcCsunSleepDataVo ds:csunSleepDatas) {
                if(r.getDeviceId().equals(ds.getDeviceId())){
                    r.setHeartbeat(ds.getHeartbeat());
                    r.setBreath(ds.getBreath());
                    r.setInBed(ds.getInBed());
                    r.setStatus(ds.getStatus());
                }
            }
        }
        for (RoomSleepInfo r:roomSleepInfolist) {
            List<DmcDeviceAlert> dmcDeviceAlerts = new ArrayList<>();
            for (DmcDeviceAlert ds:deviceAlerts) {
                if(r.getDeviceId().equals(ds.getDeviceId())){
                    dmcDeviceAlerts.add(ds);
                    r.setDeviceAlert(dmcDeviceAlerts);
                    break;
                }
            }
        }
        //查询报警信息
        List<DmcDeviceAlert> deviceAlertList = dmcRpcService.queryAllSleepAlert(ids);
        Integer total = 0,//总人数
                online = 0,//在线
                offLine  = 0,//离线
                inbed = 0,//在床
                notInBed = 0,//离床
                man = 0,//男
                women = 0,//女
                rollAlert = 0,//翻身
                offlineAlert = 0,//离线报警
                leaveBedAlert = 0,//离床报警
                breathAlert = 0,//呼吸异常
                beatHeartAlert = 0;//心跳异常
        //床垫报警按类别计数
        for (DmcDeviceAlert s:deviceAlertList) {
            switch (s.getAlertType()){
                case 8 : rollAlert++;
                break;
                case 10 : offlineAlert++;
                break;
                case 11 : leaveBedAlert++;
                break;
                case 17 : breathAlert++;
                break;
                case 18 : beatHeartAlert++;
                break;
            }
        }
        //统计性别
        for (RoomSleepInfo r:roomSleepInfolist) {
            if(r.getSex() == 0){
                man++;
            }
            if(r.getSex() == 1){
                women++;
            }
        }
        //统计床垫状态

            for (RoomSleepInfo s:roomSleepInfolist) {
                if(s.getStatus().equals("offline")){
                    offLine++;
                }
                if(s.getStatus().equals("online")){
                    online++;
                    if(s.getInBed() == 0){
                        notInBed++;
                    }else {
                        inbed++;
                    }
                }
            }

        SleepIndexVo sleepIndexVo = new SleepIndexVo();
        sleepIndexVo.setBreathAlert(breathAlert);
        sleepIndexVo.setBeatHeartAlert(beatHeartAlert);
        sleepIndexVo.setInbed(inbed);
        sleepIndexVo.setLeaveBedAlert(leaveBedAlert);
        sleepIndexVo.setMan(man);
        sleepIndexVo.setNotInBed(notInBed);
        sleepIndexVo.setOffLine(offLine);
        sleepIndexVo.setOfflineAlert(offlineAlert);
        sleepIndexVo.setOnline(online);
        sleepIndexVo.setRollAlert(rollAlert);
        sleepIndexVo.setWomen(women);
        sleepIndexVo.setTotal(roomSleepInfolist.size());
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), sleepIndexVo);
    }

    @PostMapping("/querySleepInbed")
    public Wrapper querySleepInbed(String time){
        Long groupId = getLoginAuthDto().getGroupId();
        List<RoomSleepInfo> roomSleepInfos = roomService.roomSleepInfo(groupId);
        ArrayList<Long> ids = new ArrayList<>();
        if(roomSleepInfos.size()>0){
            for (RoomSleepInfo r:roomSleepInfos){
                ids.add(r.getOldmanId());
            }
        }
        //查询绑定了床垫的老人
        List<RoomSleepInfo> sleepInfos = dmcRpcService.querySleepBind(ids);
        ids = new ArrayList<>();
        for (RoomSleepInfo r:sleepInfos) {
            ids.add(r.getDeviceId());
        }
        //查询床垫时间段是否在床
        List<CsunSleepDataReqVo> csunSleepDataReqVos = dmcRpcService.querySleepInbed(ids,time);
        Integer inbed = 0;
        for (RoomSleepInfo r:sleepInfos) {
            for(CsunSleepDataReqVo c:csunSleepDataReqVos){
                if(r.getDeviceId().equals(c.getDeviceId())){
                    if(c.getInBed() == 1){
                        inbed++;
                    }
                    break;
                }
            }
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.0%");
        String format = decimalFormat.format(inbed.doubleValue() / sleepInfos.size());
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), format);
    }
}
